package com.spzx.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IPaymentInfoService paymentInfoService;

    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @ResponseBody
    @RequestMapping("/submitAlipay/{orderNo}")
    public AjaxResult submitAlipay(@PathVariable("orderNo") String orderNo){
        String from=alipayService.submitAlipay(orderNo);
        return success(from);
    }

    //支付宝同步回调
    @Operation(summary = "支付宝同步调用")
    @GetMapping("/callback/return")
    public String callBack() {
        // 同步回调给用户展示信息
        return "redirect:/" + AlipayConfig.return_order_url;
    }

    //异步回调
    @ResponseBody
    @RequestMapping("/callback/notify")
    public String alipayNotify(@RequestParam Map<String,String> paramMap,HttpServletRequest request){
        log.info("异步通知返回结果"+paramMap);
        log.info("alipayNotify执行了");
        //验签
        boolean signVerified=false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
           e.printStackTrace();
        }
        if (signVerified){
            String trade_status=paramMap.get("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status)||"TRADE_FINISHED".equals(trade_status)){
                paymentInfoService.updatePaymentStatus(paramMap,2);
                return "success";
            }else {
                return "failure";
            }
        }
        return "failure";
    }
}
